<template>
  <section class="redpacket-account-main">
    <section class="main-search merge">
      <span class="svg-container">
        <svg-icon icon-class="search" />
      </span>
      <el-input
        v-model.trim="listQuery.name"
        placeholder="输入名称搜索"
        class="search-input"
        @keyup.enter.native="handleFilter"
      />
      <section class="search-btn">
        <el-button class="filter-item" type="primary" @click="handleFilter">搜索</el-button>
        <el-button type="primary" @click="handleReset">重置</el-button>
      </section>
    </section>
    <section class="main-buttons">
      <section class="main-buttons-title">
        <span>企业账号管理</span>
      </section>
      <section class="main-buttons-btns">
        <el-button style="margin-left: 10px" @click="handleCreate">新建</el-button>
      </section>
    </section>

    <section class="main-table">
      <v-table :list="list" tag="redpacketaccountmain" :list-loading="listLoading" :filter-column="filtercolumn">
        <el-table-column label="操作" fixed="right" align="center" min-width="100" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="mini"
              @click="handlePublish(scope.row)"
            >{{ scope.row.accountStatus === "ZHZT01" ? "禁用" : "启用" }}
            </el-button>
            <el-button type="text" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
            <el-button
              v-if="scope.row.accountType === 'INCOME'"
              type="text"
              size="mini"
              @click="handleRecord(scope.row)"
            >交易
            </el-button>
          </template>
        </el-table-column>
      </v-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.limit"
        @pagination="getList"
      />
    </section>
    <el-dialog
      v-el-drag-dialog
      :destroy-on-close="true"
      :visible.sync="visible"
      :close-on-click-modal="false"
      title="新建/编辑企业账号"
      center
      width="600px"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="名称" prop="name">
          <el-input v-model.trim="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="账号" prop="accountNumber">
          <el-input v-model.trim="form.accountNumber" :disabled="state === 'update'" placeholder="请输入账号" />
        </el-form-item>

        <el-form-item
          v-if="state==='create' ||(state === 'update' && form.accountNumber=='') "
          label="确认账号"
          prop="accountNumber2"
        >
          <el-input v-model.trim="form.accountNumber2" placeholder="请输入账号" />
        </el-form-item>
        <el-form-item label="影子账号" prop="shadowAccount">
          <el-input
            v-model.trim="form.shadowAccount"
            :disabled="state === 'update' && form.shadowAccount!='' && yzFlag"
            placeholder="请输入影子账号"
          />
        </el-form-item>

        <el-form-item
          v-if="state==='create' || !yzFlag ||(state === 'update' && form.shadowAccount=='') "
          label="确认影子账号"
          prop="shadowAccount2"
        >
          <el-input v-model.trim="form.shadowAccount2" placeholder="请输入影子账号" />
        </el-form-item>
        <el-form-item label="账户类型" prop="accountType">
          <el-radio-group
            v-model.trim="form.accountType"
            :disabled="state === 'update'"
            style="width: 100%;"
          >
            <el-radio
              v-for="item in dict.ACCOUNTTPYE"
              :key="item.dictValue"
              :label="item.dictValue"
            >{{ item.dictName }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="本企业账户" prop="isEnterprise">
          <el-radio-group
            v-model.trim="form.isEnterprise"
            style="width: 100%;"
          >
            <el-radio
              v-for="item in dict.SFQYZY"
              :key="item.dictValue"
              :label="item.dictValue"
            >{{ item.dictName }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态" prop="accountStatus">
          <el-radio-group v-model="form.accountStatus">
            <el-radio label="ZHZT01">启用</el-radio>
            <el-radio label="ZHZT02">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="default" style="padding: 10px 30px" @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="state === 'create'? createSubmit() : updateSubmit()">确 定</el-button>
      </div>
    </el-dialog>

  </section>
</template>
<script>
import { queryPage, insert, update, getDictByCode, get, updateState } from './../api'
import Pagination from '@/components/Pagination'
import VTable from '@/components/Table'
import elDragDialog from '@/directive/el-drag-dialog'
import CryptoJS from '@/utils/aesJiaJM'

export default {
  name: 'RedPacketAccountMain',
  components: { VTable, Pagination },
  directives: { elDragDialog },
  data() {
    var checkNumber = (rule, value, callback) => {
      if (value === '' && this.form.accountNumber !== '') {
        callback(new Error('请确认账号'))
      } else if (value !== this.form.accountNumber) {
        callback(new Error('两次输入不一致!'))
      } else {
        callback()
      }
    }
    var checkshadow = (rule, value, callback) => {
      if (this.form.shadowAccount === '') {
        callback()
      } else {
        if (value === '') {
          callback(new Error('请确认影子账号'))
        } else if (value !== this.form.shadowAccount) {
          callback(new Error('两次输入不一致!'))
        } else {
          callback()
        }
      }
    }
    var checkshadow1 = (rule, value, callback) => {
      if (this.form.shadowAccount2 === '') {
        callback()
      } else {
        if (value === '') {
          callback(new Error('请输入影子账号'))
        } else if (value !== this.form.shadowAccount2) {
          callback(new Error('两次输入不一致'))
        } else {
          callback()
        }
      }
    }
    return {
      listQuery: {
        page: 1,
        limit: 10,
        name: ''
      },
      list: [],
      total: 0,
      listLoading: false,
      visible: false,
      state: 'create',
      form: {
        id: '',
        name: '',
        accountNumber: '',
        accountNumber2: '',
        shadowAccount: '',
        shadowAccount2: '',
        accountType: '',
        accountStatus: 'ZHZT01',
        isEnterprise: ''
      },
      rules: {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        accountNumber: [{ required: true, message: '请输入账号', trigger: 'blur' }],
        accountNumber2: [{ validator: checkNumber, trigger: 'blur' }],
        shadowAccount: [{ validator: checkshadow1, trigger: 'blur' }],
        shadowAccount2: [{ validator: checkshadow, trigger: 'blur' }],
        accountType: [{ required: true, message: '请选择账户类型', trigger: 'change' }],
        accountStatus: [{ required: true, message: '请选择状态', trigger: 'change' }],
        isEnterprise: [{ required: true, message: '请选择是否为本企业账户', trigger: 'change' }]
      },
      dict: {
        ACCOUNTTPYE: [], // 账户类型
        SFQYZY: [] // 本企业账户
      },
      yzFlag: true
    }
  },
  created() {
    this.getList()
    for (const key in this.dict) {
      this.getDict(key)
    }
  },
  methods: {
    /**
     * 启用/禁用
     */
    handlePublish(row) {
      this.$confirm(row.accountStatus === 'ZHZT01' ? '确认禁用？' : '确认启用？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateState({ id: row.id, accountStatus: row.accountStatus === 'ZHZT01' ? 'ZHZT02' : 'ZHZT01' }).then(res => {
          if (res.data.code === '200') {
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
            this.getList()
          }
        })
      }).catch(() => {

      })
    },
    getDict(code) {
      return new Promise((resolve, reject) => {
        getDictByCode(code).then(response => {
          this.dict[code] = response.data.data[0].list
        }).catch(error => {
          reject(error)
        })
      })
    },
    filtercolumn(scope, item) {
      if (item === 'accountNumber' || item === 'shadowAccount') {
        return scope.row[item] ? CryptoJS.$aesJieM(scope.row[item]) : ''
      } else {
        return scope.row[item]
      }
    },

    handleReset() {
      this.listQuery.page = 1
      this.listQuery.name = ''
      this.getList()
    },

    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },

    handleCreate() {
      console.log('form', this.form)
      for (const key in this.form) {
        if (key === 'accountStatus') {
          this.form[key] = 'ZHZT01'
        } else {
          this.form[key] = ''
        }
      }
      this.state = 'create'
      this.visible = true
    },
    /**
     * 交易记录
     * */
    handleRecord(row) {
      this.$router.push({ path: this.$filterPath('record'), query: { i: row.id }})
    },

    handleUpdate(row) {
      const ths = this
      //   	let form= {
      //     id: '',
      //     name: '',
      //     accountNumber: '',
      //     accountNumber2: '',
      //     shadowAccount:'',
      //     shadowAccount2:'',
      //     accountType:'',
      //     accountStatus: ''
      // }
      this.getData(row.id).then(res => {
        for (const key in ths.form) {
          if (key !== 'accountNumber2' && key !== 'shadowAccount2') {
            if (key === 'accountNumber' || key === 'shadowAccount') {
              const vale = res[key] ? CryptoJS.$aesJieM(res[key]) : ''
              if (key === 'shadowAccount' && vale === '') {
                this.yzFlag = false
              }
              this.form[key] = vale
              const cur = key + '2'
              this.form[cur] = vale
            } else {
              this.form[key] = res[key]
            }
          }
        }
        ths.state = 'update'
        ths.visible = true
      }).catch(() => {
        ths.$message.error('获取详情失败')
      })
    },
    getData(id) {
      return new Promise((resolve, reject) => {
        get(id).then(res => {
          if (res.data.code === '200') {
            resolve(res.data.data)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    /**
     * 新增提交
     */
    createSubmit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.3)'
          })
          const params = Object.assign({}, this.form)
          delete params.accountNumber2
          delete params.shadowAccount2
          params.accountNumber = CryptoJS.$aesJiaM(params.accountNumber)
          params.shadowAccount = params.shadowAccount ? CryptoJS.$aesJiaM(params.shadowAccount) : params.shadowAccount
          return new Promise((resolve, reject) => {
            insert(params).then(() => {
              this.dialogVisible = false
              loading.close()
              this.$message({
                title: '成功',
                message: '操作成功',
                type: 'success',
                duration: 2000
              })
              this.visible = false
              this.getList()
            }).catch(error => {
              loading.close()
              reject(error)
            })
          })
        } else {
          return false
        }
      })
    },
    /**
     * 编辑提交
     */
    updateSubmit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.3)'
          })
          const params = Object.assign({}, this.form)
          delete params.accountNumber2
          delete params.shadowAccount2
          params.accountNumber = CryptoJS.$aesJiaM(params.accountNumber)
          params.shadowAccount = params.shadowAccount ? CryptoJS.$aesJiaM(params.shadowAccount) : params.shadowAccount
          return new Promise((resolve, reject) => {
            update(params).then(() => {
              this.dialogVisible = false
              this.yzFlag = true
              loading.close()
              this.$message({
                title: '成功',
                message: '操作成功',
                type: 'success',
                duration: 2000
              })
              this.visible = false
              this.getList()
            }).catch(error => {
              loading.close()
              reject(error)
            })
          })
        } else {
          return false
        }
      })
    },
    getList(obj) {
      this.listLoading = true
      var query = {
        page: obj ? obj.page : this.listQuery.page,
        pageSize: obj ? obj.limit : this.listQuery.limit,
        name: this.listQuery.name
      }
      return new Promise((resolve, reject) => {
        queryPage(query).then(response => {
          this.list = response.data.data.rows || []
          this.total = response.data.data.total
          this.listLoading = false
        }).catch(error => {
          reject(error)
          this.listLoading = false
        })
      })
    }
  }
}
</script>
<style lang="scss">
.redpacket-account-main {
  padding: 10px;

  .main-search {
    background-color: #fff;
    padding: 0 10px;

    .svg-container {
      padding: 0 5px 0 10px;
      color: #bfced6;
      vertical-align: middle;
      display: inline-block;
    }

    .search-input {
      width: 60%;
      position: relative;

      &:after {
        content: '';
        position: absolute;
        left: -25px;
        right: 0;
        bottom: 8px;
        height: 1px;
        background: rgba(226, 227, 232, 1);
      }

      input {
        outline: none;
        background: transparent;
        border: none;
        outline: medium;
        padding: 0;

        &:focus {
          outline: none;
          background-color: transparent;
        }
      }
    }

    .search-btn {
      display: inline-block;
      float: right;

      .el-button.is-round {
        padding: 10px 30px;
        margin-right: 34px;
      }

      .search-more {
        font-size: 14px;
        font-weight: 500;
        @include font-color($mainColor);
        cursor: pointer;
        margin-left: 10px;
      }
    }

    &.merge {
      height: 50px;
      line-height: 50px;
    }
  }

  .main-buttons {
    display: flex;
    line-height: 36px;
    margin-bottom: 10px;

    .main-buttons-title {
      flex: 1;
      height: 36px;
      line-height: 36px;
      font-size: 16px;
      font-weight: bold;
      color: rgba(51, 51, 51, 1);

      .num {
        @include font-color($mainColor);
      }
    }
  }
}
</style>
